package aszm.chahaospider.parser.chahao;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import aszm.chahaospider.constants.Constants;
import aszm.chahaospider.constants.DBConn;
import aszm.chahaospider.parser.chahao.bean.Tmp_City;
import aszm.chahaospider.utils.MybatisUtils;
import aszm.chahaospider.utils.Utils;
import chaohao.mybatis.dao.CityDtoMapper;
import chaohao.mybatis.dao.TmpCityMapper;
import chaohao.mybatis.model.CityDto;
import chaohao.mybatis.model.ProviceDto;

public class CityParser {
	private static final Logger Log = Logger.getLogger(PhoneHomeParser.class.getName());
	public static Connection conn = DBConn.getConnection();

	public static List<CityDto> getCitysFromWeb(ProviceDto provice, boolean writeDB) {
		Document doc = Utils.getDocumentDoc(Constants.CHAHAO_URL + provice.getUrl());
		Elements links = doc.select("li a");
		List<CityDto> citys = parserCitys(links, provice.getId());
		if (writeDB) {
			createFile(links, provice.getId());
		}
		return citys;
	}

	/**
	 * 从数据库查询Citys
	 * 
	 * @return
	 */
	public static List<CityDto> getCitysFromDB() {
		SqlSession session = MybatisUtils.getSqlSession();
		List<CityDto> citys = session.getMapper(CityDtoMapper.class).selectAll();
		session.close();
		return citys;
	}

	public static List<Tmp_City> getTmpCitysFromDB() {
		SqlSession session = MybatisUtils.getSqlSession();
		List<Tmp_City> citys = session.getMapper(TmpCityMapper.class)
				.selectAll(Constants.CHAHAO_URL);
		session.close();
		return citys;
	}

	private static List<CityDto> parserCitys(Elements links, int id) {
		List<CityDto> citys = new ArrayList<CityDto>();
		for (Element element : links) {
			CityDto city = parser(element, id);
			Log.info(city.toString());
			citys.add(city);
		}
		return citys;
	}

	public static CityDto parser(Element provice, int provice_id) {
		CityDto tb_City = new CityDto();
		tb_City.setName(provice.html());
		tb_City.setUrl(provice.attr("href"));
		tb_City.setProviceId(provice_id);
		return tb_City;
	}

	/**
	 * 持久化Citys
	 * 
	 * @param links
	 * @param id
	 *            省份ID
	 */
	private static void createFile(Elements links, int id) {
		SqlSession session = MybatisUtils.getSqlSession();
		int count = 0;
		for (Element element : links) {
			CityDto city = parser(element, id);
			int result = session.getMapper(CityDtoMapper.class).insert(city);
			count += result;
		}
		session.commit();
		MybatisUtils.showMessages(MybatisUtils.CRUD_Enum.Add, count);
	}
}
